var express = require('express');
var cors = require('cors')
var bodyParser = require('body-parser');

var app = express();
app.use(cors());


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8001;

var router = express.Router();


// Data base
var url = "mongodb://127.0.0.1:27017";
var mongoose = require('mongoose');
var Cinema = require('./models/cinema');


var citiesFile = require('./config/TOCAvalableCities.json');

mongoose.connect(url, function (err) {
    if (err) {
        console.log("Error connected mongodb " + err);
    }
});


router.get('/', function (req, res) {
    res.json({ message: '这里是TopCinemas的后台API' });
});


router.route('/cinemas')
    .post(function (req, res) {
        var cinema = new Cinema();
        cinema.name = req.body.name;
        cinema.type = req.body.type;
        cinema.city = req.body.city;
        cinema.lat = req.body.lat;
        cinema.long = req.body.long;
        cinema.s_width = req.body.s_width;
        cinema.s_height = req.body.s_height;
        cinema.ticket_url = req.body.ticket_url;
        cinema.loc = [cinema.long, cinema.lat];

        cinema.save(function (err) {
            if (err) {
                res.send(err);
            } else {
                res.json({ message: 'Cinema created!' });
            }
        });
    })
    .get(function (req, res) {

        var city = req.query.city;

        var coords = [];
        coords[0] = req.query.long;
        coords[1] = req.query.lat;

        var queryParameters;

        if (city) {
            queryParameters = { 'city': city };
        }

        if (coords[0] && coords[1]) {
            queryParameters.loc = {
                $near: coords
            }
        }

        Cinema.find(queryParameters).exec(function(err, cinemas) {
            if (err)
                res.send(err);
            else {
                res.json(cinemas);
            }
        });
    });

router.route('/cinemas/:cinema_id')
    .get(function (req, res) {
        Cinema.findById(req.params.cinema_id, function (err, cinema) {
            if (err)
                res.send(err);
            else
                res.json(cinema);
        });
    })
    .put(function (req, res) {
        Cinema.findById(req.params.cinema_id, function (err, cinema) {
            if (err)
                rets.send(err);
            cinema.name = req.body.name;
            cinema.type = req.body.type;
            cinema.lat = req.body.lat;
            cinema.long = req.body.long;
            cinema.s_width = req.body.s_width;
            cinema.s_height = req.body.s_height;
            cinema.ticket_url = req.body.ticket_url;

            cinema.loc = [cinema.long, cinema.lat];

            cinema.save(function (err) {
                if (err) {
                    res.send(err);
                } else {
                    res.json({ message: 'Cinema updated!' });
                }
            });
        });
    })
    .delete(function (req, res) {
        Cinema.remove({
            _id: req.params.cinema_id
        }, function (err, cinema) {
            if (err)
                res.send(err);
            else 
                res.json({ message: 'Successfully deleted' });
        });
    });


router.route('/cities').get(function (req, res) {
    res.json(citiesFile);
});

app.use('/api', router);

app.listen(port, function () {
    console.log('Listening port ' + port);
});
